
import { handle_back } from "@/handle/index_send_back";
import store from "@/store";


let web_socket1 = null;

let socket_time=20*1000; //毫秒数
let local_time=0;
let timer=null; //计时器。



function formatter_socket_time(time_str){
  return time_str.slice(0,4)+"-"+time_str.slice(4,6)+"-"+time_str.slice(6,8)+" "+time_str.slice(8,10)+":"+time_str.slice(10,12)+":"+time_str.slice(12,14)
}


function websocket_init1() {
  local_time=new Date().getTime(); //当前时间毫秒数。


  try{
    web_socket1 = new WebSocket("ws://192.168.11.115:9996");
  }catch(e){
    console.log("%cwebsocket_9996初始化失败_>>","color:skyblue",e)
  }


  web_socket1.onopen = websocket_on_open1;
  web_socket1.onmessage = websocket_on_message1;
  web_socket1.onclose = websocket_on_close1;
  web_socket1.onerror = websocket_on_error1;
}



function websocket_on_open1() {

  console.log("9996 connecting ..");

  socket_time=200;

}

function websocket_on_message1(res) {

  console.log("9996 onmessage!!!");


  local_time=new Date().getTime(); //当前时间毫秒数。
  
  socket_time=new Date(formatter_socket_time((JSON.parse(res.data[0])).timestamp+"")).getTime(); //2022-01-05 09:03:31

  store.commit("set_net_disconnect",false)

  handle_back(res)
}

function websocket_on_close1() {
  console.log("%c9996 closed ..","color:skyblue");


  store.commit("set_net_disconnect",true)

  local_time=new Date().getTime(); //当前时间毫秒数。
  socket_time=20*1000;

}

function websocket_on_error1(err) {
  console.log("%c9996 error ..","color:red",err);
}

function websocket_send1(cmd, arr_param) {
  var data_formatter = {
    cmd: cmd,
    data: arr_param,
  };

  console.log("%cwebsocket_send 9996 下发指令-参数","color:skyblue",data_formatter);

  web_socket1.send(JSON.stringify(data_formatter));
}
function websocket_close1() {
  web_socket1 && web_socket1.close();
  web_socket1 = null;
}

function websocket_reconect1(){
    web_socket1=null;
    websocket_init1();
    console.log("9996 socket-主动重连---")
}


/*检查socket是否掉线---根据数据时间----*/
function check_status(){
  if((local_time-socket_time)>1000*15){
    console.log('%c socket:9996 状态已经断开 ', 'color: red;'); 
    return false;
  }else{
    return true;
  }
}

timer=setInterval(()=>{
  if(check_status()==false){
    websocket_reconect1();
  }
},1000*14);


// console.log("发送指令的socket 由于不推送数据,所以只能断开重连")


export {
  web_socket1,
  websocket_init1,
  websocket_on_open1,
  websocket_on_message1,
  websocket_on_close1,
  websocket_on_error1,
  websocket_send1,
  websocket_close1,
  websocket_reconect1
};
